package nxu.it.service.impl;

import nxu.it.model.TodoItem;
import nxu.it.service.GreetingService;
import org.noear.solon.annotation.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class GreetingServiceImpl implements GreetingService {

    private static List<TodoItem> todoList;
    private static ConcurrentHashMap<Integer, TodoItem>[] itemMaps;


    static {
        TodoItem[] arr = new TodoItem[]{
                new TodoItem(1, "写作业", true),
                new TodoItem(2, "看电影", false),
                new TodoItem(3, "洗衣服", true)
        };

        todoList = new ArrayList<>();
        itemMaps = new ConcurrentHashMap[arr.length];

        for (TodoItem item : arr) {
            todoList.add(item);
        }


        for (int i = 0; i < arr.length; i++) {
            TodoItem item = arr[i];
            ConcurrentHashMap<Integer, TodoItem> map = new ConcurrentHashMap<>();
            map.put(item.getId(), item);
            itemMaps[i] = map;
        }
    }

    @Override
    public List<TodoItem> getAllItems() {
        return todoList;
    }

    @Override
    public TodoItem getItemById(int id) {
        for (ConcurrentHashMap<Integer, TodoItem> map : itemMaps) {
            TodoItem item = map.get(id);
            if (item != null) {
                return item;
            }
        }
        return null;
    }

    @Override
    public void addItem(TodoItem item) {
        todoList.add(item);
        ConcurrentHashMap<Integer, TodoItem> map = new ConcurrentHashMap<>();
        map.put(item.getId(), item);
        itemMaps = Arrays.copyOf(itemMaps, itemMaps.length + 1);
        itemMaps[itemMaps.length - 1] = map;
    }

    @Override
    public void updateItem(TodoItem item) {
        for (int i = 0; i < todoList.size(); i++) {
            if (todoList.get(i).getId() == item.getId()) {
                todoList.set(i, item);
                break;
            }
        }
        for (ConcurrentHashMap<Integer, TodoItem> map : itemMaps) {
            if (map.containsKey(item.getId())) {
                map.put(item.getId(), item);
                break;
            }
        }
    }

    @Override
    public void deleteItem(int id) {
        todoList.removeIf(item -> item.getId() == id);
        for (int i = 0; i < itemMaps.length; i++) {
            if (itemMaps[i].containsKey(id)) {
                itemMaps[i].remove(id);
                break;
            }
        }
    }

    @Override
    public int getNextId() {
        // 获取当前所有事项的最大ID，然后加1作为下一个ID
        int maxId = todoList.stream()
                .mapToInt(TodoItem::getId)
                .max()
                .orElse(0);
        return maxId + 1;
    }
}
